﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using ShopB2C.DBUtilities;
using ShopB2C.DBUtilities.SqlDbHelper;
using ShopB2C.Entity;
using ShopB2C.Interfaces;

namespace ShopB2C.SQLDataAccess
{
    public class ProductOperate : IProductOperate
    {
        #region 存储过程名称
        /// <summary>
        /// 获取商品基础信息
        /// </summary>
        private const string _getBasic = "Product_Basic_Select";
        /// <summary>
        /// 删除部件
        /// </summary>
        private const string _partDelete = "Product_Part_Delete";
        /// <summary>
        /// 批量更新部件
        /// </summary>
        private const string _partUpdate = "Product_Part_BatchUpdate";
        /// <summary>
        /// 
        /// </summary>
        private const string _partSave = "Product_Part_Save";
        /// <summary>
        /// 保存商品基础信息
        /// </summary>
        private const string _saveBasic = "Product_Basic_Save";
        /// <summary>
        /// 获取商品扩展图片列表
        /// </summary>
        private const string _saveImage = "Product_Image_Save";
        /// <summary>
        /// 改变商品分类
        /// </summary>
        private const string _changeClass = "Product_Basic_ChangeClass";
        /// <summary>
        /// 设置封面
        /// </summary>
        private const string _setCover = "Product_Image_SetCover";
        /// <summary>
        /// 删除图片
        /// </summary>
        private const string _deleteImage = "Product_Image_Delete";
        /// <summary>
        /// 保存商品详细信息/包装方式/售后服务
        /// </summary>
        private const string _saveDetails = "Product_Details_Save";
        /// <summary>
        /// 保存属性
        /// </summary>
        private const string _saveProperty = "Product_Property_Save";
        /// <summary>
        /// 删除商品
        /// </summary>
        private const string _deleteProduct = "Product_Delete";
        /// <summary>
        /// 更改激活状态
        /// </summary>
        private const string _active = "Product_Basic_ChangeActive";
        /// <summary>
        /// 更新库存数
        /// </summary>
        private const string _updateSotck = "Product_Basic_UpdateStockCount";
        /// <summary>
        /// 设置上架时间
        /// </summary>
        private const string _saleDateTime = "Product_Basic_SetSaleDateTime";
        /// <summary>
        /// 打折
        /// </summary>
        private const string _discount = "Product_Discount_General";
        /// <summary>
        /// 保存扩展信息
        /// </summary>
        private const string _saveExtend = "Product_Extend_Save";
        /// <summary>
        /// 删除扩展
        /// </summary>
        private const string _deleteExtend = "Product_Extend_Delete";
        /// <summary>
        /// 保存会员折扣
        /// </summary>
        private const string _discountMember = "Product_Discount_Member";
        /// <summary>
        /// 保存相关产品
        /// </summary>
        private const string _saveRelate = "Product_Relate_Save";
        /// <summary>
        /// 更新图片描述
        /// </summary>
        private const string _updateImageDesc = "Product_Image_UpdateDescription";

        #endregion


        public ProductOperate(string connectionString)
        {
            DbBase.ConnectionString = connectionString;
        }

        #region 商品基础信息

        /// <summary>
        /// 获取商品基础信息
        /// </summary>
        public ProductEntity GetBasicById(int productId)
        {
            ProductEntity product = null;
            DbParams<SqlParameter> sqlParams = new DbParams<SqlParameter>();
            sqlParams.Add<Int32>("@ProductId" , productId).SqlDbType = SqlDbType.Int;
            SqlDataReader reader = SqlDbProcedure.ExecuteReader(_getBasic , sqlParams.ToArray);
            if (reader.HasRows)
            {
                product = new ProductEntity();
                while (reader.Read())
                {
                    product.ProductName = reader["ProductName"].ToString();
                    product.ClassId = Convert.ToInt32(reader["ClassId"]);
                    product.Description = reader["Description"].ToString();
                    product.DisCount = Convert.ToDouble(reader["DisCount"]);
                    product.IsActive = Convert.ToBoolean(reader["IsActive"]);
                    product.KeyWords = reader["KeyWords"].ToString();
                    product.Price = Convert.ToDecimal(reader["Price"]);
                    product.ProductId = Convert.ToInt32(reader["ProductId"]);
                    product.ProductNo = reader["ProductNo"].ToString();
                    product.SaleDateTime = Convert.ToDateTime(reader["SaleDateTime"]);
                    product.StockCount = Convert.ToInt32(reader["StockCount"]);
                    product.ImageName = reader["ImageName"].ToString();
                    product.ClickCount = Convert.ToInt32(reader["ClickCount"]);
                    product.ReplyCount = Convert.ToInt32(reader["ReplyCount"]);
                    product.GradeValue = Convert.ToDecimal(reader["GradeValue"]);
                    product.SalesCount = Convert.ToInt32(reader["SalesCount"]);
                    product.SubName = reader["SubName"].ToString();
                    product.BrandId = Convert.ToInt32(reader["BrandId"]);

                }
            }
            reader.Close();

            return product;
        }
        /// <summary>
        /// 保存商品基础信息
        /// </summary>
        public int SaveProductBasic(ProductEntity product)
        {
            int result = 0;

            DbParams<SqlParameter> parameters = new DbParams<SqlParameter>();
            parameters.Add("@ProductId" , product.ProductId).SqlDbType = SqlDbType.Int;
            parameters.Add("@ProductName" , 255 , product.ProductName).SqlDbType = SqlDbType.NVarChar;
            parameters.Add("@ProductNo" , 10 , product.ProductNo).SqlDbType = SqlDbType.NVarChar;
            parameters.Add("@Description" , 1000 , product.Description).SqlDbType = SqlDbType.NVarChar;
            parameters.Add("@KeyWords" , 1000 , product.KeyWords).SqlDbType = SqlDbType.NVarChar;
            parameters.Add("@Price" , product.Price).SqlDbType = SqlDbType.Decimal;
            parameters.Add("@DisCount" , product.DisCount).SqlDbType = SqlDbType.Float;
            parameters.Add("@StockCount" , product.StockCount).SqlDbType = SqlDbType.Int;
            parameters.Add("@SaleDateTime" , product.SaleDateTime).SqlDbType = SqlDbType.DateTime;
            parameters.Add("@IsActive" , product.IsActive).SqlDbType = SqlDbType.Bit;
            parameters.Add("@ClassId" , product.ClassId).SqlDbType = SqlDbType.Int;
            parameters.Add("@BrandId" , product.BrandId).SqlDbType = SqlDbType.Int;
            parameters.Add("@SubName" , 20 , product.SubName).SqlDbType = SqlDbType.NVarChar;

            result = Convert.ToInt32(SqlDbProcedure.ExecuteScalar(_saveBasic , parameters.ToArray));

            return result;
        }
        /// <summary>
        /// 更改商品分类
        /// </summary>
        /// <param name="productId">关联的商品ID</param>
        /// <param name="classId">更改的分类ID</param>
        public int ChangeClass(int productId , int classId)
        {
            int result = 0;
            SqlParameter[] parameters = 
            {
               new SqlParameter("@ProductId",SqlDbType.Int),
               new SqlParameter("@ClassId",SqlDbType.Int)
            };

            parameters[0].Value = productId;
            parameters[1].Value = classId;

            result = SqlDbProcedure.ExecuteNonQuery(_changeClass , parameters);
            return result;
        }
        /// <summary>
        /// 删除商品:注意,执行此操作将从商品表,商品扩展表,商品详细表删除所有和改商品相关的资料,请谨慎操作
        /// </summary>
        /// <returns>返回受影响的行数</returns>
        public int DeleteProduct(int productId)
        {
            int result = 0;
            SqlParameter[] parameters =
           {
               new SqlParameter("@ProductId",SqlDbType.Int)
           };
            parameters[0].Value = productId;

            result = SqlDbProcedure.ExecuteNonQuery(_deleteProduct , parameters);

            return result;
        }
        /// <summary>
        /// 保存会员价格
        /// </summary>
        /// <param name="memberPrice">会员价实体类</param>
        /// <returns>被影响的行</returns>
        public int SaveMemberDiscount(UserLevelEntity memberPrice)
        {
            int result = 0;
            SqlParameter[] parameters = 
            {
                new SqlParameter("@Levelid",SqlDbType.Int){Value = memberPrice.LevelId },
                new SqlParameter("@ProductId",SqlDbType.Int){Value = memberPrice.Sequence},
                new SqlParameter("@Discount",SqlDbType.Float){Value = memberPrice.Discount},
                new SqlParameter("@IsDiscount",SqlDbType.Bit){Value = memberPrice.IsDiscount}
            };
            result = SqlDbProcedure.ExecuteNonQuery(_discountMember , parameters);

            return result;
        }

        #endregion


        #region 属性

        /// <summary>
        /// 保存属性
        /// </summary>
        /// <param name="propertyList">属性列表</param>
        /// <returns>受影响的行</returns>
        public int SaveProperty(List<ProductPropertyEntity> propertyList)
        {
            int result = 0;

            foreach (var item in propertyList)
            {
                SqlParameter[] parameters = 
             {
                 new SqlParameter("@ProductId",SqlDbType.Int),
                 new SqlParameter("@PropertyId",SqlDbType.Int),
                 new SqlParameter("@ProductPropertyId",SqlDbType.Int),
                 new SqlParameter("@PropertyValId",SqlDbType.Int)
             };

                parameters[0].Value = item.ProductId;
                parameters[1].Value = item.PropertyId;
                parameters[2].Value = item.ProductPropertyId;
                parameters[3].Value = item.PropertyValId;

                result += SqlDbProcedure.ExecuteNonQuery(_saveProperty , parameters);
            }

            return result;
        }

        #endregion

        #region 图片
        /// <summary>
        /// 保存商品图片扩展
        /// </summary>
        /// <returns>返回受影响的行数</returns>
        public int SaveImage(ProductImageEntity para)
        {
            int result = 0;
            SqlParameter[] parameters = 
            {
               new SqlParameter("@ImageId",SqlDbType.Int),
               new SqlParameter("@ImageName",SqlDbType.NVarChar,50),
               new SqlParameter("@Title",SqlDbType.NVarChar,255),
               new SqlParameter("@Description",SqlDbType.NVarChar,1000),
               new SqlParameter("@IsCover",SqlDbType.Bit),
               new SqlParameter("@ProductId",SqlDbType.Int),
               new SqlParameter("@Sequence",SqlDbType.Int)
            };

            parameters[0].Value = para.ImageId;
            parameters[1].Value = para.ImageName;
            parameters[2].Value = para.Title;
            parameters[3].Value = para.Description;
            parameters[4].Value = para.IsCover;
            parameters[5].Value = para.ProductId;
            parameters[6].Value = para.Sequence;

            result = SqlDbProcedure.ExecuteNonQuery(_saveImage , parameters);

            return result;
        }
        /// <summary>
        /// 设置封面
        /// </summary>
        /// <param name="productId">关联的商品ID</param>
        /// <returns>受影响的行</returns>
        public int SetCover(int imageId)
        {
            int result = 0;
            SqlParameter[] parameters =
            {
                new SqlParameter("@ImageId",SqlDbType.Int)
            };
            parameters[0].Value = imageId;
            result = SqlDbProcedure.ExecuteNonQuery(_setCover , parameters);
            return result;
        }
        /// <summary>
        /// 删除商品图片扩展
        /// </summary>
        /// <returns>返回受影响的行数</returns>
        public List<ProductImageEntity> DeleteImage(string[] para)
        {

            List<ProductImageEntity> imageList = new List<ProductImageEntity>();
            foreach (var item in para)
            {
                SqlParameter[] parameters = 
                {
                   new  SqlParameter("@ImageId",SqlDbType.Int)
                };
                parameters[0].Value = item;
                SqlDataReader reader = SqlDbProcedure.ExecuteReader(_deleteImage , parameters);
                while (reader.Read())
                {
                    imageList.Add(new ProductImageEntity()
                    {
                        ImageName = reader["ImageName"].ToString() ,
                        ProductId = Convert.ToInt32(reader["ProductId"])
                    });
                }
                reader.Close();
            }
            return imageList;
        }
        /// <summary>
        /// 更新图片描述
        /// </summary>
        /// <param name="imageId">关联的图片ID</param>
        /// <param name="title">图片标题</param>
        /// <param name="description">图片描述</param>
        /// <param name="sequence">排序ID</param>
        /// <returns>受影响的行</returns>
        public int UpdateImageDescription(int imageId , string title , string description , int sequence)
        {
            return SqlDbProcedure.ExecuteNonQuery(_updateImageDesc ,
                new SqlParameter[] {
                    new SqlParameter("@ImageId",SqlDbType.Int){Value=imageId}
                    ,new SqlParameter("@Title",SqlDbType.NVarChar,50){Value=title}
                    ,new SqlParameter("@Description",SqlDbType.NVarChar,255){Value= description}
                    ,new SqlParameter("@Sequence",SqlDbType.Int){Value=sequence} });
        }
        #endregion

        #region 详细信息/售后服务/包装方式
        /// <summary>
        /// 保存商品详细信息/售后服务/包装方式
        /// </summary>
        /// <returns>返回受影响的行数</returns>
        public int SaveDetails(ProductDetailsEntity para)
        {
            int result = 0;
            SqlParameter[] parameters = 
            {
               new SqlParameter("@ProductId",SqlDbType.Int),
               new SqlParameter("@Details",SqlDbType.NVarChar,3950),
               new SqlParameter("@Services",SqlDbType.NVarChar,50)
            };

            parameters[0].Value = para.ProductId;
            parameters[1].Value = para.Detail;
            parameters[2].Value = para.Services;

            result = SqlDbProcedure.ExecuteNonQuery(_saveDetails , parameters);

            return result;
        }

        #endregion


        #region 批量操作
        /// <summary>
        /// 更改激活状态
        /// </summary>
        /// <param name="productId">商品ID</param>
        /// <param name="IsActive">激活状态</param>
        /// <returns>被更改的行数</returns>
        public int ChangeActive(int productId , bool IsActive)
        {
            int result = 0;
            SqlParameter[] parameters = 
            {
                new SqlParameter("@ProductId",SqlDbType.Int),
                new SqlParameter("@IsActive",SqlDbType.Bit)
            };

            parameters[0].Value = productId;
            parameters[1].Value = IsActive;

            result = SqlDbProcedure.ExecuteNonQuery(_active , parameters);

            return result;
        }
        /// <summary>
        /// 更新库存数
        /// </summary>
        /// <param name="productId">商品ID</param>
        /// <param name="stockCount">库存数</param>
        /// <returns>受影响的行</returns>
        public int UpdateStock(int productId , int stockCount)
        {
            int result = 0;
            SqlParameter[] parameters = 
            {
                new SqlParameter("@ProductId",SqlDbType.Int),
                new SqlParameter("@StockCount",SqlDbType.Int)
            };

            parameters[0].Value = productId;
            parameters[1].Value = stockCount;

            result = SqlDbProcedure.ExecuteNonQuery(_updateSotck , parameters);

            return result;
        }
        /// <summary>
        /// 更新实际上架时间
        /// </summary>
        /// <param name="ProductId">商品ID</param>
        /// <param name="saleDateTime">实际上架时间</param>
        /// <returns>受影响的行</returns>
        public int UpdateSalesDateTime(int productId , DateTime saleDateTime)
        {
            int result = 0;
            SqlParameter[] parameters = 
            {
                new SqlParameter("@ProductId",SqlDbType.Int),
                new SqlParameter("@SaleDateTime",SqlDbType.DateTime)
            };

            parameters[0].Value = productId;
            parameters[1].Value = saleDateTime;

            result = SqlDbProcedure.ExecuteNonQuery(_saleDateTime , parameters);

            return result;
        }
        /// <summary>
        /// 打折
        /// </summary>
        /// <param name="productId">商品ID</param>
        /// <param name="discount">折扣率</param>
        /// <returns>受影响的行数</returns>
        public int Discount(int productId , double discount)
        {
            int result = 0;
            SqlParameter[] parameters = 
            {
                new SqlParameter("@ProductId",SqlDbType.Int),
                new SqlParameter("@Discount",SqlDbType.Float)
            };

            parameters[0].Value = productId;
            parameters[1].Value = discount;

            result = SqlDbProcedure.ExecuteNonQuery(_discount , parameters);

            return result;
        }
        #endregion

        #region 扩展属性

        /// <summary>
        /// 保存扩展属性
        /// </summary>
        /// <param name="extnedEntity">关联的扩展参数</param>
        /// <returns>受影响的行</returns>
        public int SaveExtend(ProductExtendEntity extnedEntity)
        {
            int result = 0;

            SqlParameter[] parameters = 
            {
                new SqlParameter("@ProductId",SqlDbType.Int)
                , new SqlParameter("@ExtendKey",SqlDbType.NVarChar,50)
                , new SqlParameter("@ExtendValue",SqlDbType.NVarChar,1000)
                , new SqlParameter("@Sequence",SqlDbType.Int)
                , new SqlParameter("@ExtendId",SqlDbType.Int)
            };

            parameters[0].Value = extnedEntity.ProductId;
            parameters[1].Value = extnedEntity.ExtendKey;
            parameters[2].Value = extnedEntity.ExtendValue;
            parameters[3].Value = extnedEntity.Sequence;
            parameters[4].Value = extnedEntity.ExtendId;

            result = SqlDbProcedure.ExecuteNonQuery(_saveExtend , parameters);

            return result;
        }
        /// <summary>
        /// 删除扩展属性
        /// </summary>
        /// <param name="extendId">扩展属性主键ID</param>
        /// <returns>受影响的行</returns>
        public int DeleteExtendItem(int extendId)
        {
            int result = 0;

            SqlParameter[] parameters = 
           {
               new SqlParameter("@ExtendId",SqlDbType.Int)
           };

            parameters[0].Value = extendId;
            result = SqlDbProcedure.ExecuteNonQuery(_deleteExtend , parameters);

            return result;
        }

        #endregion

        #region 产品部件
        /// <summary>
        /// 
        /// </summary>
        /// <param name="partId"></param>
        /// <param name="title"></param>
        /// <param name="IsValid"></param>
        /// <param name="partType"></param>
        /// <param name="count"></param>
        /// <param name="classId"></param>
        /// <param name="sequence"></param>
        /// <param name="ids"></param>
        /// <returns></returns>
        public int ProductPartSave(int partId , string title , bool IsValid , int partType , int count , int classId , int sequence , string ids , string modekKey)
        {
            int result = 0;
            SqlParameter[] paramerters =
            {
                new SqlParameter("@PartId",SqlDbType.Int){ Value = partId},
                new SqlParameter("@PartName",SqlDbType.NVarChar,50){ Value= title},
                new SqlParameter("@IsValid",SqlDbType.Bit){ Value=IsValid},
                new SqlParameter("@PartType",SqlDbType.Int){ Value=partType},
                new SqlParameter("@Count",SqlDbType.Int){ Value= count},
                new SqlParameter("@ClassId",SqlDbType.Int){ Value=classId},
                new SqlParameter("@Sequence",SqlDbType.Int){ Value=sequence},
                new SqlParameter("@Ids",SqlDbType.VarChar,4000){ Value = ids },
                new SqlParameter("@ModuleKey",SqlDbType.NVarChar,50){ Value = modekKey}
            };
            result = SqlDbProcedure.ExecuteNonQuery(_partSave , paramerters);

            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="partId"></param>
        /// <returns></returns>
        public int ProductPartDelete(int partId)
        {
            SqlParameter[] parameters = 
            {
                new SqlParameter("@PartId",SqlDbType.Int){ Value = partId}
            };

            return SqlDbProcedure.ExecuteNonQuery(_partDelete , parameters);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="iv"></param>
        /// <param name="se"></param>
        /// <returns></returns>
        public int ProductPartUpdate(string id , string iv , string se)
        {
            int result = 0;
            SqlParameter[] parameters = 
            {
                new SqlParameter("@PartId",SqlDbType.VarChar,2000){Value = id },
                new SqlParameter("@IsValid",SqlDbType.VarChar,2000){Value =iv },
                new SqlParameter("@Sequence",SqlDbType.VarChar,2000){Value = se }
            };

            result = SqlDbProcedure.ExecuteNonQuery(_partUpdate , parameters);

            return result;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="relateIds"></param>
        /// <param name="PrimaryKey"></param>
        /// <returns></returns>
        public int SaveRelate(string relateIds , int PrimaryKey , string title)
        {
            int result = 0;
            SqlParameter[] parameters = 
            {
                new SqlParameter("@RelateIds",SqlDbType.VarChar,4000){Value = relateIds},
                new SqlParameter("@Title",SqlDbType.NVarChar,50){Value =title },
                new SqlParameter("@ProductId",SqlDbType.Int){Value = PrimaryKey}
            };
            result = SqlDbProcedure.ExecuteNonQuery(_saveRelate , parameters);
            return result;
        }

        #endregion



    }
}
